package com.atguigu.crowd.handler;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.config.OSSProperties;
import com.atguigu.crowd.entity.vo.*;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author yzt
 * @create 2021-09-24 11:05
 */
@Controller
public class ProjectHandler {


    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MySQLRemoteService mySQLRemoteService;

    @RequestMapping("/get/detail/project/{projectId}")
    public String getDetailProById(@PathVariable("projectId") Integer projectId,Model model){

        ResultEntity<DetailProjectVO> detailProjectVOEntity = mySQLRemoteService.getDetailProjectById(projectId);

        if("SUCCESS".equals(detailProjectVOEntity.getOperationResult())){
            model.addAttribute("detailProjectVO",detailProjectVOEntity.getQueryData());
        }
        return "project-detail";
    }


    @RequestMapping("/create/confirm")
    public String saveConfirm(MemberConfirmInfoVO confirmInfoVO,Model model,HttpSession session){

        ProjectVO projectVO = (ProjectVO) session.getAttribute("temple_project");

        if(projectVO == null){
            throw new RuntimeException("后台出错！");
        }
        projectVO.setMemberConfirmInfoVO(confirmInfoVO);

        MemberLoginVO loginMember = (MemberLoginVO) session.getAttribute("loginMember");
        Integer memberId = loginMember.getId();

        ResultEntity<String> saveProjectEntity = mySQLRemoteService.saveProjectVORemote(projectVO,memberId);

        if("FAILED".equals(saveProjectEntity.getOperationResult())){
            model.addAttribute("message",saveProjectEntity.getOperationMessage());
            return "project-confirm";
        }

        session.removeAttribute("temple_project");

        return "redirect:http://localhost/project/create/success/page";
    }

    @ResponseBody
    @RequestMapping("/create/save/return")
    public ResultEntity<String> saveReturn(ReturnVO returnVO,HttpSession session){

        try {
            ProjectVO projectVO = (ProjectVO) session.getAttribute("temple_project");

            if(projectVO == null){
                return ResultEntity.failed("后台出错");
            }

            List<ReturnVO> returnVOList = projectVO.getReturnVOList();
            if(returnVOList == null || returnVOList.size() == 0){
                returnVOList = new ArrayList<>();
                projectVO.setReturnVOList(returnVOList);
            }

            returnVOList.add(returnVO);

            session.setAttribute("temple_project",projectVO);

            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }

    }

    @ResponseBody
    @RequestMapping("/create/upload/return/picture")
    public ResultEntity<String> uploadReturnPicture(@RequestParam("returnPicture")
                                                     MultipartFile returnPicture) throws IOException {

        ResultEntity<String> returnPicEntity = CrowdUtil.uploadFileToOss(ossProperties.getEndPoint(), ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(), returnPicture.getInputStream(),
                ossProperties.getBucketName(), ossProperties.getBucketDomain(),
                returnPicture.getOriginalFilename());

        return returnPicEntity;
    }

    @RequestMapping("/create/project/information")
    public String saveProjectBasicInfo(ProjectVO projectVO,
                                       MultipartFile headerPicture,
                                       List<MultipartFile> detailPictureList,
                                       HttpSession session, Model model) throws IOException {

        boolean headPictureEmpty = headerPicture.isEmpty();
        if(headPictureEmpty){
            model.addAttribute("message","头图不能为空！");
            return "project-launch";
        }
        ResultEntity<String> uploadPicEntity = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(), ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(), headerPicture.getInputStream(),
                ossProperties.getBucketName(), ossProperties.getBucketDomain(),
                headerPicture.getOriginalFilename());

        if("FAILED".equals(uploadPicEntity)){
            model.addAttribute("message","头图上传失败！");
            return "project-launch";
        }
        String headPicPath = uploadPicEntity.getQueryData();
        projectVO.setHeaderPicturePath(headPicPath);

        if(detailPictureList == null || detailPictureList.size()==0){
            model.addAttribute("message","详情图片不能为空！");
            return "project-launch";
        }

        List<String> detailPicturePathList = new ArrayList<>();

        for (MultipartFile detailPicture:detailPictureList) {
            if(detailPicture.isEmpty()){
                model.addAttribute("message","详情图片不能为空！");
                return "project-launch";
            }
            ResultEntity<String> updateDetailEntity = CrowdUtil.uploadFileToOss(ossProperties.getEndPoint(), ossProperties.getAccessKeyId()
                    , ossProperties.getAccessKeySecret(), detailPicture.getInputStream(),
                    ossProperties.getBucketName(), ossProperties.getBucketDomain(),
                    detailPicture.getOriginalFilename());

            if("FAILED".equals(updateDetailEntity)){
                model.addAttribute("message","详情图片上传失败！");
                return "project-launch";
            }

            String detailPicPath = updateDetailEntity.getQueryData();
            detailPicturePathList.add(detailPicPath);
        }
        projectVO.setDetailPicturePathList(detailPicturePathList);

        session.setAttribute("temple_project",projectVO);

        return "redirect:http://localhost/project/return/info/page";
    }
}
